<?php
use Illuminate\Support\Facades\Redis;
use App\Models\Activitys;
use App\Models\MediaAd;
use App\Models\TemplateConfig;
//获得真实IP
function PUB_getRealip()
{
    $onlineip_str = '';
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $onlineip_str = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $onlineip_str = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $onlineip_str = getenv('REMOTE_ADDR');
    } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $onlineip_str = $_SERVER['REMOTE_ADDR'];
    }

    if (strpos($onlineip_str, ',') > 0) {
        $real_ip = explode(',', $onlineip_str)[0];
    } else {
        $real_ip = $onlineip_str;
    }

    return $real_ip;
}

function PUB_setRedis($key, $value, $db = 'default')
{
    $redis = Redis::connection($db);
    $redis->set($key, $value);
    return $redis;
}

function PUB_setTimeRedis($key, $value, $db = 'default')
{
    $time=time()+600;
    $redis = Redis::connection($db);
    $redis->set($key, $value);
    $redis->EXPIREAT($key,$time);
    return $redis;
}


function PUB_getRedis($key, $db = 'default')
{

    $redis = Redis::connection($db);
    $data = $redis->get($key);
    return $data;

}

//初始化活动Activity
function PUB_initActivity($ad_id)
{
    if (!Redis::exists('Activitys' . $ad_id)) {


        if (Redis::ttl('Activitys' . $ad_id)=='-2'){
            $pos=intval(date('H',time()));
            $s=intval(date('i'));
            if($s>=30){
                $pos+=1;
            }
            $activitys = Activitys::
            select('sort', 'activitys.*')
                ->join('media_activity_relation', 'activitys.id', 'media_activity_relation.activity_id')
                ->join('media_ad', 'media_activity_relation.media_ad_id', 'media_ad.id')
                ->join('advertisers', 'advertisers.id', 'activitys.advertiser_id')
                ->where('advertisers.system_status', 'CUSTOMER_STATUS_NORMAL')
                ->where('media_ad.id', $ad_id)

                ->Where(function ($query){
                    $query->where('state', 0)->orWhere('state', 3);
                })
                ->Where(function ($query) use ($pos){
                    $query->where('time_series', null)->orWhere(DB::raw('substring(time_series,'.$pos.',1)'), 1);
                })
                ->where('end_date', '>=', date("Y-m-d", time()))
                ->where('start_date', '<=', date("Y-m-d", time()))
                ->orderBy('media_activity_relation.sort')
                ->get();
//        dd($activitys->toArray()[0]['Region']);
            if ($activitys) {
                PUB_setTimeRedis('Activitys' . $ad_id,serialize($activitys));
            }

        }
    }

}


//初始化模板顺序配置
function PUB_initTemplateConfig($ad_id)
{

    if (!Redis::exists('TemplateConfig_' . $ad_id)) {
      //  $time=time()*600;
     //   Redis::EXPIREAT('TemplateConfig_' . $ad_id,$time);
        $TemplateConfig = TemplateConfig::where('ad_id',$ad_id)
            ->leftJoin('templates','templates.id','template_config.template_id')
            ->where('template_config.sort','>','0')
            ->orderBy('template_config.sort')
            ->get();
        if ($TemplateConfig) {
            PUB_setRedis('TemplateConfig_' . $ad_id, serialize($TemplateConfig),'DB1');
        }
    }

}

//初始化模板
function PUB_initTemplate()
{

    if (!Redis::exists('Template')) {
      //  $time=time()*600;
     //   Redis::EXPIREAT('Template',$time);
        $data = Template::selectRaw("id,template_src,template_href,template_name")
            ->where('state','=','1')->get()->toArray();

        PUB_setRedis('Template', serialize($data));
    }

}

function PUB_initMediaAD()
{
    $redis = Redis::connection('DB1');
    if (!$redis->exists('MediaAD')) {
    //    $time=time()*600;
     //   $redis->EXPIREAT('MediaAD',$time);
        // $redis->set('MediaAD', serialize(MediaAd::get()));
        PUB_setRedis('MediaAD', serialize(MediaAd::get()), 'DB1');
    }
}


function PUB_initIpLibrary()
{
    $redis = Redis::connection('DB2');
    $IpLibrary = \App\Models\IpLibrary::select('region_code', 'start_ip_int', 'end_ip_int')->get()->toArray();
    $redis->set('IpLibrary', serialize($IpLibrary));

}

function PUB_initIpLibrary1()
{

    $redis = Redis::connection('DB2');
    $IpLibrary = \App\Models\IpLibrary::select('region_code', 'start_ip_int', 'end_ip_int')->get()->toArray();
//    print$IpLibrary[0]);
    foreach ($IpLibrary as $ip) {
        $redis->sadd('IpLibrarySet', serialize($ip));
    }

}

function PUB_initIpLibrary2()
{

    $redis = Redis::connection('DB2');
    if (!$redis->exists('IpLibraryZadd')) {

        $IpLibrary = \App\Models\IpLibrary::select('region_code', 'start_ip_int', 'end_ip_int')->get()->toArray();

//        print_r(count($IpLibrary));
        foreach ($IpLibrary as $k => $ip) {

            $redis->zadd('IpLibraryZadd', $ip['end_ip_int'], serialize($ip));
//        break;
        }
    }

}

function PUB_initUserIp($ip)
{
    $redis = Redis::connection('DB2');
//    if (!$redis->exists('IpLibraryZadd')) {
        return $obj = \App\Models\IpLibrary::select('region_code', 'start_ip_int', 'end_ip_int')
            ->where('start_ip_int', '<=', ip2long($ip))
            ->where('end_ip_int', '>=', ip2long($ip))
            ->first()
            ->toArray();
//    }
    $n = 4294967296;// n的值是总IP数，确保一定会超过结束区间
    $long = ip2long($ip);
    $rows = $redis->zRangeByScore('IpLibraryZadd', $long, $long + $n, ['limit' => [0, 1]]);
    if (!empty($rows)) {
        foreach ($rows as $row) {
            $obj = unserialize($row);
            if ($obj['start_ip_int'] <= $long && $long <= $obj['end_ip_int']) {
                return $obj;
            }
        }
    }

}
function PUB_initUserIp2($ip,$device_id)
{
//    $stime = time();
//    $ip = "124.58.180.5";
    $redis = Redis::connection();
    if(!$redis->exists($device_id.'_IP')){
        $address = readip2($ip);
//    $etime = time();
//
//    $utime = $etime - $stime;
//    dump('address:',$address);
//    dd('use time:'.$utime);

        PUB_setRedis($device_id.'_IP',serialize($address));
    }
//    return $address;

}
function readip2($ip){
    $fname = base_path().'/ip.csv';
    $file = fopen($fname,"r");

    while(! feof($file))
    {
        $csvFile=fgetcsv($file,50);
//        dd($csvFile);
//        $line=str_replace("\t","_",$csvFile[0]);
        $line=$csvFile[0];
        $csvArr[]=$line;
    }
    unset($csvArr[count($csvArr)-1]);
    unset($csvArr[0]);
    $csvArr=array_values($csvArr);
    $search=ip2long($ip);
    $height=count($csvArr)-1;
    $low=0;
    $restArr=[];
    $i=0;
    while($low<=$height){
        $i++;
        $mid=floor(($low+$height)/2);//获取中间数

        $newcsvarr=explode("\t",$csvArr[$mid]);
//        dump(ip2long($newcsvarr[0]),$search);

        if((ip2long($newcsvarr[0])<=$search)&&(ip2long($newcsvarr[1])>=$search)){
            $restArr= $newcsvarr;//返回
            break;
        }elseif(ip2long($newcsvarr[1])<=$search){//当中间值小于所查值时，则$mid左边的值都小于$search，此时要将$mid赋值给$low
            $low=$mid+1;
        }elseif(ip2long($newcsvarr[1])>=$search){//中间值大于所查值,则$mid右边的所有值都大于$search,此时要将$mid赋值给$height
            $height=$mid-1;
        }

    }

//    dd($i);

//    dd($i);
    fclose($file);
    return $restArr;
}
function readip($ip){
    $ip_num = $ip_n = bindec(decbin(ip2long($ip)));

    echo $ip_num;

    $fname = base_path().'/ip.csv';

    $fd = @fopen($fname, 'rb');
    $size = filesize($fname);//得到文件大小，才好采用二分法
    echo ' - size is : ';
    echo $size;
    echo '
';
    $len = $size;

    $adress = '';

    $sm = 0;
    $em = $size;

    $mid = ceil(($em - $sm)/2);
    $b = true;
    $ci = 0; //走的次数
    while($b){

        dump("$sm , $em , ".$mid.' - ');
        fseek($fd,$mid);
        $line = fread($fd, 80);
        dump($line);
        $x = explode("\n",$line);
        $qline = $line;
        $line = '';
//        dd($x);
        foreach($x as $k=>$v){
            if(preg_match("/^\\d+,\\d+,.*?,.*?,.*?$/",$v)){
                $line = $v;
            }
        }

        if($line==''){//最后的处理，直接命中
            fseek($fd,$sm);
            $line = fread($fd,$size-$mid);
            $x = explode("\n",$line);
            foreach($x as $k=>$v){
                if(preg_match("/^\\d{8,10},\\d{8,10},.*?,.*?,.*?/",$v)){
                    $line = $v;
                    $arr = explode(',',$line);

                    $start = intval($arr[0]);
                    $end = intval($arr[1]);
                    if($ip_num >= $start && $ip_num <= $end){
                        echo '命中'.$line;
                        $address = $arr[2].$arr[3].$arr[4];
                        return $address;
                        $b = false;
                        break;
                    }

                }
            }
            break;
        }

        $arr = explode(',',$line);
dump('$arr:'.$arr);
        $start = $arr[0];
        $end = $arr[1];

        if($ip_num < $start ){
            echo '向前走';
            $em = $mid;
            $mid = $sm + ceil(($em - $sm)/2);
        }

        if( $ip_num > $end){
            echo '向后走'." # $start @ $end #";
            $sm = $mid;
            $mid = $mid + ceil(($em - $sm)/2);
        }

        if($ip_num >= $start && $ip_num <= $end){
            echo '命中';
            $address = $arr[2].$arr[3].$arr[4];
            $b = false;
        }

        echo ' -- ';
        echo $line;
        echo '';

        if($mid<2)$b = false;
        if($ci>100) $b = false;//说明没有找到
        $ci++;
    }


}